<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理后台 - API Key管理系统</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus@2.4.4/dist/index.css" crossorigin="anonymous">
    <!-- Element Plus Icons - 使用内联样式替代外部CSS -->
    <style>
        /* Element Plus Icons 基础样式 */
        .el-icon {
            display: inline-block;
            font-size: inherit;
            height: 1em;
            width: 1em;
            line-height: 1;
            text-transform: none;
            vertical-align: -0.15em;
            fill: currentColor;
            overflow: hidden;
        }
    </style>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background-color: #f5f7fa;
        }

        .admin-layout {
            display: flex;
            min-height: 100vh;
        }

        /* 左侧菜单样式 */
        .sidebar {
            width: 250px;
            background: #304156;
            color: white;
            flex-shrink: 0;
            box-shadow: 2px 0 6px rgba(0, 0, 0, 0.1);
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #3a4a5c;
            text-align: center;
        }

        .sidebar-title {
            font-size: 18px;
            font-weight: 600;
            margin: 0;
            color: #fff;
        }

        .sidebar-subtitle {
            font-size: 12px;
            color: #8492a6;
            margin: 5px 0 0 0;
        }

        .sidebar-menu {
            padding: 20px 0;
        }

        .menu-item {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            background: none;
            color: #bfcbd9;
            width: 100%;
            text-align: left;
            font-size: 14px;
        }

        .menu-item:hover {
            background: #3a4a5c;
            color: #fff;
        }

        .menu-item.active {
            background: #409eff;
            color: #fff;
        }

        .menu-item i {
            margin-right: 10px;
            font-size: 16px;
        }

        .sidebar-footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px;
            border-top: 1px solid #3a4a5c;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
            font-weight: 600;
        }

        .user-name {
            font-size: 14px;
            color: #bfcbd9;
        }

        /* 主内容区域样式 */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .content-header {
            background: white;
            padding: 16px 24px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .content-title {
            font-size: 20px;
            font-weight: 600;
            color: #303133;
            margin: 0;
        }

        .content-body {
            flex: 1;
            padding: 24px;
            overflow-y: auto;
        }

        /* 统计卡片样式 - 参考admin-review.html */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .stat-card.success::before {
            background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
        }

        .stat-card.warning::before {
            background: linear-gradient(135deg, #e6a23c 0%, #f56c6c 100%);
        }

        .stat-card.danger::before {
            background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
        }

        .stat-icon {
            display: none; /* 隐藏图标，使用纯文字样式 */
        }

        .stat-content {
            width: 100%;
        }

        .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 8px;
        }

        .stat-label {
            font-size: 14px;
            color: #606266;
        }

        .status-tag {
            font-size: 12px;
        }

        /* 操作栏样式 */
        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 16px;
        }

        .action-left {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        .action-right {
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: wrap;
        }

        /* 表格容器样式 */
        .table-container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* API Key单元格样式 */
        .api-key-cell {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .api-key-text {
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 12px;
            background: #f5f7fa;
            padding: 4px 8px;
            border-radius: 4px;
            border: 1px solid #dcdfe6;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        /* 分页容器样式 */
        .pagination-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        /* 文本颜色样式 */
        .success-text {
            color: #67c23a !important;
        }

        .warning-text {
            color: #e6a23c !important;
        }

        .danger-text {
            color: #f56c6c !important;
        }

        .expired-text {
            color: #f56c6c;
            font-weight: bold;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .admin-layout {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                position: relative;
            }

            .sidebar-footer {
                position: relative;
            }

            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }

            .content-body {
                padding: 16px;
            }

            .action-bar {
                flex-direction: column;
                align-items: stretch;
            }

            .action-left,
            .action-right {
                justify-content: center;
            }
        }

        /* 内容区域样式 */
        .menu-content {
            /* 移除display: none，让Vue的v-show指令控制显示隐藏 */
        }
    </style>
</head>
<body>
<div id="app">
    <div class="admin-layout">
        <!-- 左侧菜单 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <h1 class="sidebar-title">管理后台</h1>
                <p class="sidebar-subtitle">API Key管理系统</p>
            </div>

            <div class="sidebar-menu">
                <button class="menu-item" :class="{ active: activeMenu === 'apikeys' }" @click="setActiveMenu('apikeys')">
                    <i class="el-icon-key"></i>
                    <span>API Key管理</span>
                </button>
                <button class="menu-item" :class="{ active: activeMenu === 'applications' }" @click="setActiveMenu('applications')">
                    <i class="el-icon-document-checked"></i>
                    <span>申请审核</span>
                </button>
                <button class="menu-item" :class="{ active: activeMenu === 'statistics' }" @click="setActiveMenu('statistics')">
                    <i class="el-icon-data-analysis"></i>
                    <span>API Key统计</span>
                </button>
                <button class="menu-item" :class="{ active: activeMenu === 'logs' }" @click="setActiveMenu('logs')">
                    <i class="el-icon-document"></i>
                    <span>系统日志</span>
                </button>
            </div>

            <div class="sidebar-footer">
                <div class="user-info">
                    <div class="user-avatar">A</div>
                    <div>
                        <div class="user-name">管理员</div>
                        <el-button type="text" size="small" @click="logout" style="color: #8492a6; padding: 0;">
                            退出登录
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content">
            <div class="content-header">
                <h2 class="content-title">{{ getPageTitle() }}</h2>
                <div>
                    <el-button @click="refreshData" :loading="loading">
                        <el-icon><Refresh /></el-icon>
                        刷新
                    </el-button>
                </div>
            </div>

            <div class="content-body">
                <!-- API Key管理内容 -->
            <div v-show="activeMenu === 'apikeys'" class="menu-content">
                    <!-- 统计卡片区域 -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-icon">
                                <el-icon><Key /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ stats.totalKeys }}</div>
                                <div class="stat-label">总API Key数</div>
                            </div>
                        </div>
                        <div class="stat-card success">
                            <div class="stat-icon active">
                                <el-icon><Key /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ stats.activeKeys }}</div>
                                <div class="stat-label">活跃API Key</div>
                            </div>
                        </div>
                        <div class="stat-card warning">
                            <div class="stat-icon expired">
                                <el-icon><Key /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ stats.expiredKeys }}</div>
                                <div class="stat-label">过期API Key</div>
                            </div>
                        </div>
                        <div class="stat-card danger">
                            <div class="stat-icon">
                                <el-icon><DataAnalysis /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ stats.totalRequests }}</div>
                                <div class="stat-label">总请求数</div>
                            </div>
                        </div>
                    </div>

                    <!-- 操作栏 -->
                    <div class="action-bar">
                        <div class="action-left">
                            <el-button type="primary" @click="showCreateDialog">
                                <el-icon><Plus /></el-icon>
                                新建API Key
                            </el-button>
                            <el-button @click="refreshData">
                                <el-icon><Refresh /></el-icon>
                                刷新
                            </el-button>
                        </div>
                        <div class="action-right">
                            <el-input
                                v-model="searchForm.keyword"
                                placeholder="搜索API Key名称或描述"
                                style="width: 200px; margin-right: 10px;"
                                @keyup.enter="searchApiKeys">
                                <template #prefix>
                                    <el-icon><Search /></el-icon>
                                </template>
                            </el-input>
                            <el-select
                                v-model="searchForm.status"
                                placeholder="状态筛选"
                                style="width: 120px; margin-right: 10px;"
                                clearable>
                                <el-option label="活跃" value="active"></el-option>
                                <el-option label="禁用" value="inactive"></el-option>
                                <el-option label="过期" value="expired"></el-option>
                            </el-select>
                            <el-button type="primary" @click="searchApiKeys">搜索</el-button>
                            <el-button @click="resetSearch">
                                <el-icon><RefreshLeft /></el-icon>
                                重置
                            </el-button>
                        </div>
                    </div>

                    <!-- API Key列表 -->
                    <div class="table-container">
                        <el-table
                            :data="apiKeyList"
                            v-loading="loading"
                            stripe
                            style="width: 100%">
                            <el-table-column prop="phoneNumber" label="手机号" width="150">
                                <template #default="scope">
                                    {{ scope.row.phoneNumber || '未关联' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="API Key" width="350">
                                <template #default="scope">
                                    <div class="api-key-cell">
                                        <code class="api-key-text">{{ scope.row.keyValue }}</code>
                                        <el-button
                                            type="text"
                                            size="small"
                                            @click="copyToClipboard(scope.row.keyValue)"
                                            title="复制API Key">
                                            <el-icon><CopyDocument /></el-icon>
                                        </el-button>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="权限" width="150">
                                <template #default="scope">
                                    <el-tag
                                        v-for="permission in getPermissions(scope.row.permissions)"
                                        :key="permission"
                                        size="small"
                                        style="margin-right: 5px;">
                                        {{ permission }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="状态" width="100">
                                <template #default="scope">
                                    <el-tag :type="getStatusType(scope.row.status)">
                                        {{ getStatusText(scope.row.status) }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="expiresAt" label="过期时间" width="180">
                                <template #default="scope">
                                    <span :class="{ 'expired-text': isExpired(scope.row.expiresAt) }">
                                        {{ formatDate(scope.row.expiresAt) }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="createdAt" label="创建时间" width="180">
                                <template #default="scope">
                                    {{ formatDate(scope.row.createdAt) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="250" fixed="right">
                                <template #default="scope">
                                    <el-button
                                        type="text"
                                        size="small"
                                        @click="showApiKeyStats(scope.row)">
                                        <el-icon><TrendCharts /></el-icon>
                                        统计
                                    </el-button>
                                    <el-button
                                        type="text"
                                        size="small"
                                        @click="showApiKeyLogs(scope.row)">
                                        <el-icon><Document /></el-icon>
                                        日志
                                    </el-button>
                                    <el-button
                                        type="text"
                                        size="small"
                                        @click="editApiKey(scope.row)">
                                        <el-icon><Edit /></el-icon>
                                        编辑
                                    </el-button>
                                    <el-button
                                        type="text"
                                        size="small"
                                        :class="scope.row.status === 'active' ? 'warning-text' : 'success-text'"
                                        @click="toggleApiKeyStatus(scope.row)">
                                        {{ scope.row.status === 'active' ? '禁用' : '启用' }}
                                    </el-button>
                                    <el-button
                                        type="text"
                                        size="small"
                                        class="danger-text"
                                        @click="deleteApiKey(scope.row)">
                                        <el-icon><Delete /></el-icon>
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 分页 -->
                        <div class="pagination-container">
                            <el-pagination
                                v-model:current-page="pagination.currentPage"
                                v-model:page-size="pagination.pageSize"
                                :page-sizes="[10, 20, 50, 100]"
                                :total="pagination.total"
                                layout="total, sizes, prev, pager, next, jumper"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange">
                            </el-pagination>
                        </div>
                    </div>
                </div>

                <!-- 申请审核内容 -->
                <div v-show="activeMenu === 'applications'" class="menu-content">
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-icon">
                                <el-icon><Document /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ applicationStats.totalApplications }}</div>
                                <div class="stat-label">总申请数</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon warning">
                                <el-icon><Document /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ applicationStats.pendingApplications }}</div>
                                <div class="stat-label">待审核</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon active">
                                <el-icon><Document /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ applicationStats.approvedApplications }}</div>
                                <div class="stat-label">已通过</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon expired">
                                <el-icon><Document /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ applicationStats.rejectedApplications }}</div>
                                <div class="stat-label">已拒绝</div>
                            </div>
                        </div>
                    </div>

                    <!-- 申请列表 -->
                    <div class="table-container">
                        <el-table
                            :data="applicationList"
                            v-loading="applicationsLoading"
                            stripe
                            style="width: 100%">
                            <el-table-column prop="phoneNumber" label="手机号" width="120"></el-table-column>
                            <el-table-column prop="remark" label="申请说明" width="200">
                                <template #default="scope">
                                    <span :title="scope.row.remark">{{ scope.row.remark || '-' }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="状态" width="100">
                                <template #default="scope">
                                    <el-tag :type="getApplicationStatusType(scope.row.status)">
                                        {{ getApplicationStatusText(scope.row.status) }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="applyTime" label="申请时间" width="180">
                                <template #default="scope">
                                    {{ formatDate(scope.row.applyTime) }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="reviewer" label="审核人" width="100">
                                <template #default="scope">
                                    {{ scope.row.reviewer || '-' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="reviewTime" label="审核时间" width="180">
                                <template #default="scope">
                                    {{ scope.row.reviewTime ? formatDate(scope.row.reviewTime) : '-' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="200" fixed="right">
                                <template #default="scope">
                                    <el-button
                                        type="text"
                                        size="small"
                                        @click="viewApplicationDetail(scope.row)">
                                        查看详情
                                    </el-button>
                                    <el-button
                                        v-if="scope.row.status === 'PENDING'"
                                        type="text"
                                        size="small"
                                        class="success-text"
                                        @click="approveApplication(scope.row)">
                                        通过
                                    </el-button>
                                    <el-button
                                        v-if="scope.row.status === 'PENDING'"
                                        type="text"
                                        size="small"
                                        class="danger-text"
                                        @click="rejectApplication(scope.row)">
                                        拒绝
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 分页 -->
                        <div class="pagination-container">
                            <el-pagination
                                v-model:current-page="applicationPagination.currentPage"
                                v-model:page-size="applicationPagination.pageSize"
                                :page-sizes="[10, 20, 50, 100]"
                                :total="applicationPagination.total"
                                layout="total, sizes, prev, pager, next, jumper"
                                @size-change="handleApplicationSizeChange"
                                @current-change="handleApplicationCurrentChange">
                            </el-pagination>
                        </div>
                    </div>
                </div>

                <!-- API Key统计内容 -->
                <div v-show="activeMenu === 'statistics'" class="menu-content">
                    <div class="stats-row">
                        <div class="stat-card success">
                            <div class="stat-icon">
                                <el-icon><TrendCharts /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ stats.totalRequests }}</div>
                                <div class="stat-label">总请求数</div>
                            </div>
                        </div>
                        <div class="stat-card warning">
                            <div class="stat-icon">
                                <el-icon><Timer /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ stats.avgResponseTime || 0 }}ms</div>
                                <div class="stat-label">平均响应时间</div>
                            </div>
                        </div>
                        <div class="stat-card danger">
                            <div class="stat-icon">
                                <el-icon><Warning /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ stats.errorCount || 0 }}</div>
                                <div class="stat-label">错误请求数</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon">
                                <el-icon><Key /></el-icon>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value">{{ stats.totalKeys }}</div>
                                <div class="stat-label">总API Key数</div>
                            </div>
                        </div>
                    </div>

                    <!-- 统计图表 -->
                    <div class="chart-container" style="margin-top: 20px;">
                        <div id="statisticsChart" style="width: 100%; height: 400px; border: 1px solid #e4e7ed; border-radius: 4px;"></div>
                    </div>

                    <!-- 筛选条件 -->
                    <div class="action-bar" style="margin-top: 20px;">
                        <div class="action-left">
                            <el-date-picker
                                v-model="statisticsFilter.dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD">
                            </el-date-picker>
                            <el-select
                                v-model="statisticsFilter.apiKeyId"
                                placeholder="选择API Key"
                                style="width: 200px; margin-left: 10px;"
                                clearable>
                                <el-option
                                    v-for="key in apiKeyList"
                                    :key="key.id"
                                    :label="key.name"
                                    :value="key.id">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="action-right">
                            <el-button type="primary" @click="loadStatisticsData">查询</el-button>
                            <el-button @click="resetStatisticsFilter">重置</el-button>
                        </div>
                    </div>
                </div>

                <!-- 系统日志内容 -->
                <div v-show="activeMenu === 'logs'" class="menu-content">
                    <!-- 筛选条件 -->
                    <div class="action-bar">
                        <div class="action-left">
                            <el-date-picker
                                v-model="logsFilter.dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD">
                            </el-date-picker>
                            <el-input
                                v-model="logsFilter.apiKeyId"
                                placeholder="输入API Key值"
                                style="width: 200px; margin-left: 10px;"
                                clearable>
                            </el-input>
                            <el-select
                                v-model="logsFilter.statusCode"
                                placeholder="状态码"
                                style="width: 120px; margin-left: 10px;"
                                clearable>
                                <el-option label="200" value="200"></el-option>
                                <el-option label="400" value="400"></el-option>
                                <el-option label="401" value="401"></el-option>
                                <el-option label="403" value="403"></el-option>
                                <el-option label="404" value="404"></el-option>
                                <el-option label="500" value="500"></el-option>
                            </el-select>
                        </div>
                        <div class="action-right">
                            <el-button type="primary" @click="loadSystemLogsData">查询</el-button>
                            <el-button @click="resetLogsFilter">重置</el-button>
                        </div>
                    </div>

                    <!-- 日志列表 -->
                    <div class="table-container">
                        <el-table
                            :data="systemLogsList"
                            v-loading="logsLoading"
                            stripe
                            style="width: 100%">
                            <el-table-column prop="apiKeyValue" label="API Key" width="200">
                                <template #default="scope">
                                    <code style="font-size: 12px;">{{ scope.row.apiKeyValue }}</code>
                                </template>
                            </el-table-column>
                            <el-table-column prop="requestPath" label="接口" width="200"></el-table-column>
                            <el-table-column prop="requestMethod" label="方法" width="80"></el-table-column>
                            <el-table-column prop="responseStatus" label="状态码" width="80">
                                <template #default="scope">
                                    <el-tag :type="scope.row.responseStatus >= 400 ? 'danger' : 'success'" size="small">
                                        {{ scope.row.responseStatus }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="responseTime" label="响应时间(ms)" width="120"></el-table-column>
                            <el-table-column prop="clientIp" label="客户端IP" width="120"></el-table-column>
                            <el-table-column prop="userAgent" label="User Agent" width="200" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="accessTime" label="访问时间" width="180">
                                <template #default="scope">
                                    {{ formatDate(scope.row.accessTime) }}
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 分页 -->
                        <div class="pagination-container">
                            <el-pagination
                                v-model:current-page="logsPagination.currentPage"
                                v-model:page-size="logsPagination.pageSize"
                                :page-sizes="[10, 20, 50, 100]"
                                :total="logsPagination.total"
                                layout="total, sizes, prev, pager, next, jumper"
                                @size-change="handleLogsSizeChange"
                                @current-change="handleLogsCurrentChange">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 总体统计弹窗 -->
    <el-dialog
        v-model="dialogs.overallStats"
        title="总体统计"
        width="800px"
        @close="handleClose">
        <div id="overallStatsChart" style="width: 100%; height: 400px;"></div>
    </el-dialog>

    <!-- 系统日志弹窗 -->
    <el-dialog
        v-model="dialogs.systemLogs"
        title="系统日志"
        width="1000px"
        @close="handleClose">
        <el-table
            :data="systemLogs"
            v-loading="logsLoading"
            stripe
            style="width: 100%"
            max-height="400">
            <el-table-column prop="apiKeyValue" label="API Key" width="200">
                <template #default="scope">
                    <code style="font-size: 12px;">{{ scope.row.apiKeyValue }}</code>
                </template>
            </el-table-column>
            <el-table-column prop="requestPath" label="接口" width="150"></el-table-column>
            <el-table-column prop="requestMethod" label="方法" width="80"></el-table-column>
            <el-table-column prop="responseStatus" label="状态码" width="80">
                <template #default="scope">
                    <el-tag :type="scope.row.responseStatus >= 400 ? 'danger' : 'success'" size="small">
                        {{ scope.row.responseStatus }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="responseTime" label="响应时间(ms)" width="120"></el-table-column>
            <el-table-column prop="accessTime" label="访问时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.accessTime) }}
                </template>
            </el-table-column>
        </el-table>
    </el-dialog>

    <!-- API Key统计弹窗 -->
    <el-dialog
        v-model="dialogs.apiKeyStats"
        :title="`API Key统计 - ${currentApiKey?.name}`"
        width="800px"
        @close="handleClose">
        <div id="apiKeyStatsChart" style="width: 100%; height: 400px;"></div>
    </el-dialog>

    <!-- API Key日志弹窗 -->
    <el-dialog
        v-model="dialogs.apiKeyLogs"
        :title="`API Key日志 - ${currentApiKey?.name}`"
        width="1000px"
        @close="handleClose">
        <el-table
            :data="apiKeyLogs"
            v-loading="logsLoading"
            stripe
            style="width: 100%"
            max-height="400">
            <el-table-column prop="requestPath" label="接口" width="150"></el-table-column>
            <el-table-column prop="requestMethod" label="方法" width="80"></el-table-column>
            <el-table-column prop="responseStatus" label="状态码" width="80">
                <template #default="scope">
                    <el-tag :type="scope.row.responseStatus >= 400 ? 'danger' : 'success'" size="small">
                        {{ scope.row.responseStatus }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="responseTime" label="响应时间(ms)" width="120"></el-table-column>
            <el-table-column prop="accessTime" label="访问时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.accessTime) }}
                </template>
            </el-table-column>
        </el-table>
    </el-dialog>

    <!-- 申请详情弹窗 -->
    <el-dialog
        v-model="dialogs.applicationDetail"
        title="申请详情"
        width="600px"
        @close="handleClose">
        <div v-if="currentApplication">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="申请ID">{{ currentApplication.id }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ currentApplication.phoneNumber }}</el-descriptions-item>
                <el-descriptions-item label="申请说明">{{ currentApplication.remark || '无' }}</el-descriptions-item>
                <el-descriptions-item label="浏览器指纹">{{ currentApplication.fingerprint || '无' }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="getApplicationStatusType(currentApplication.status)">
                        {{ currentApplication.statusText }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="申请时间">{{ formatDate(currentApplication.applyTime) }}</el-descriptions-item>
                <el-descriptions-item v-if="currentApplication.reviewTime" label="审核时间">
                    {{ formatDate(currentApplication.reviewTime) }}
                </el-descriptions-item>
                <el-descriptions-item v-if="currentApplication.reviewer" label="审核人">
                    {{ currentApplication.reviewer }}
                </el-descriptions-item>
            </el-descriptions>
        </div>
        <template #footer>
            <div v-if="currentApplication && currentApplication.status === 'pending'">
                <el-button @click="dialogs.applicationDetail = false">关闭</el-button>
                <el-button type="success" @click="approveApplication(currentApplication)">通过</el-button>
                <el-button type="danger" @click="rejectApplication(currentApplication)">拒绝</el-button>
            </div>
            <div v-else>
                <el-button @click="dialogs.applicationDetail = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 创建/编辑API Key弹窗 -->
    <el-dialog
        v-model="dialogs.createEdit"
        :title="isEditing ? '编辑API Key' : '创建API Key'"
        width="500px"
        @close="handleClose">
        <el-form
            :model="apiKeyForm"
            :rules="formRules"
            ref="apiKeyFormRef"
            label-width="100px">
            <el-form-item label="名称" prop="name">
                <el-input v-model="apiKeyForm.name" placeholder="请输入API Key名称"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description">
                <el-input
                    v-model="apiKeyForm.description"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入描述信息">
                </el-input>
            </el-form-item>
            <el-form-item label="权限" prop="permissions">
                <el-checkbox-group v-model="apiKeyForm.permissions">
                    <el-checkbox label="read">读取</el-checkbox>
                    <el-checkbox label="write">写入</el-checkbox>
                    <el-checkbox label="delete">删除</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="过期时间" prop="expiresAt">
                <el-date-picker
                        v-model="apiKeyForm.expiresAt"
                        type="datetime"
                        placeholder="选择过期时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogs.createEdit = false">取消</el-button>
                    <el-button type="primary" @click="submitApiKeyForm" :loading="submitting">
                        {{ isEditing ? '更新' : '创建' }}
                    </el-button>
                </span>
        </template>
    </el-dialog>
</div>

<!-- Vue 3 -->
<script src="https://unpkg.com/vue@3.3.8/dist/vue.global.js" crossorigin="anonymous"></script>
<!-- Element Plus -->
<script src="https://unpkg.com/element-plus@2.4.4/dist/index.full.js" crossorigin="anonymous"></script>
<!-- Element Plus Icons -->
<script src="https://unpkg.com/@element-plus/icons-vue@2.1.0/dist/index.iife.js" crossorigin="anonymous"></script>
<!-- ECharts -->
<script src="https://unpkg.com/echarts@5.4.3/dist/echarts.min.js" crossorigin="anonymous"
        onerror="console.error('ECharts加载失败，使用备用方案')"></script>

<script>
    const {createApp, ref, reactive, onMounted, nextTick} = Vue;
    const {ElMessage, ElMessageBox} = ElementPlus;

    // ECharts 兼容性检查
    if (typeof echarts === 'undefined') {
        console.warn('ECharts未加载，图表功能将不可用');
        window.echarts = {
            init: () => ({
                setOption: () => {
                },
                resize: () => {
                },
                dispose: () => {
                }
            })
        };
    }
    const app = createApp({
        setup() {
            // 响应式数据
            const loading = ref(false);
            const applicationsLoading = ref(false);
            const logsLoading = ref(false);
            const submitting = ref(false);
            const isEditing = ref(false);
            const activeMenu = ref('apikeys');

            // 统计数据
            const stats = reactive({
                totalKeys: 0,
                activeKeys: 0,
                expiredKeys: 0,
                totalRequests: 0
            });

            // 申请统计数据
            const applicationStats = reactive({
                totalApplications: 0,
                pendingApplications: 0,
                approvedApplications: 0,
                rejectedApplications: 0
            });

            // API Key列表
            const apiKeyList = ref([]);
            // 申请列表
            const applicationList = ref([]);

            // 搜索表单
            const searchForm = reactive({
                keyword: '',
                status: ''
            });

            // 分页
            const pagination = reactive({
                currentPage: 1,
                pageSize: 10,
                total: 0
            });

            // 申请分页
            const applicationPagination = reactive({
                currentPage: 1,
                pageSize: 10,
                total: 0
            });

            // 弹窗状态
            const dialogs = reactive({
                overallStats: false,
                systemLogs: false,
                apiKeyStats: false,
                apiKeyLogs: false,
                createEdit: false,
                applicationDetail: false
            });

            // 当前操作的API Key和申请
            const currentApiKey = ref(null);
            const currentApplication = ref(null);

            // 日志数据
            const systemLogs = ref([]);
            const apiKeyLogs = ref([]);
            const systemLogsList = ref([]);

            // 统计和日志筛选条件
            const statisticsFilter = reactive({
                dateRange: [],
                apiKeyId: ''
            });

            const logsFilter = reactive({
                dateRange: [],
                apiKeyId: '',
                statusCode: ''
            });

            // 日志分页
            const logsPagination = reactive({
                currentPage: 1,
                pageSize: 10,
                total: 0
            });

            // API Key表单
            const apiKeyForm = reactive({
                name: '',
                description: '',
                permissions: [],
                expiresAt: ''
            });

            // 表单验证规则
            const formRules = {
                name: [
                    {required: true, message: '请输入API Key名称', trigger: 'blur'}
                ],
                permissions: [
                    {required: true, message: '请选择至少一个权限', trigger: 'change'}
                ]
            };

            // API请求函数
            const apiRequest = async (url, options = {}) => {
                try {
                    // 如果是相对路径，添加后端服务器地址
                    const fullUrl = url.startsWith('http') ? url : `http://localhost:8080${url}`;
                    
                    const response = await fetch(fullUrl, {
                        headers: {
                            'Content-Type': 'application/json',
                            ...options.headers
                        },
                        ...options
                    });

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    return await response.json();
                } catch (error) {
                    console.error('API request failed:', error);
                    ElMessage.error('请求失败: ' + error.message);
                    throw error;
                }
            };

            // 获取页面标题
            const getPageTitle = () => {
                const titles = {
                    'apikeys': 'API Key管理',
                    'applications': '申请审核',
                    'statistics': 'API Key统计',
                    'logs': '系统日志'
                };
                return titles[activeMenu.value] || 'API Key管理';
            };

            // 设置活跃菜单
            const setActiveMenu = (menu) => {
                activeMenu.value = menu;
                if (menu === 'apikeys') {
                    loadApiKeys();
                    loadStats();
                } else if (menu === 'applications') {
                    loadApplications();
                    loadApplicationStats();
                } else if (menu === 'statistics') {
                    loadApiKeys(); // 加载API Key列表用于筛选
                    loadStatisticsData();
                } else if (menu === 'logs') {
                    loadApiKeys(); // 加载API Key列表用于筛选
                    loadSystemLogsData();
                }
            };

            // 退出登录
            const logout = () => {
                ElMessageBox.confirm('确定要退出登录吗？', '确认退出', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    window.location.href = '/admin-login.html';
                }).catch(() => {});
            };

            // 加载统计数据
            const loadStats = async () => {
                try {
                    const data = await apiRequest('/api/apikeys/stats');
                    Object.assign(stats, data);
                } catch (error) {
                    console.error('Failed to load stats:', error);
                }
            };

            // 加载申请统计数据
            const loadApplicationStats = async () => {
                try {
                    const response = await apiRequest('/api/admin/applications/statistics');
                    // 处理后端返回的数据结构
                    if (response.success && response.data) {
                        applicationStats.totalApplications = (response.data.PENDING || 0) + (response.data.APPROVED || 0) + (response.data.REJECTED || 0);
                        applicationStats.pendingApplications = response.data.PENDING || 0;
                        applicationStats.approvedApplications = response.data.APPROVED || 0;
                        applicationStats.rejectedApplications = response.data.REJECTED || 0;
                    }
                } catch (error) {
                    console.error('Failed to load application stats:', error);
                }
            };

            // 加载API Key列表
            const loadApiKeys = async () => {
                loading.value = true;
                try {
                    const params = new URLSearchParams({
                        page: pagination.currentPage - 1,
                        size: pagination.pageSize
                    });

                    if (searchForm.keyword) {
                        params.append('keyword', searchForm.keyword);
                    }
                    if (searchForm.status) {
                        params.append('status', searchForm.status);
                    }

                    const data = await apiRequest(`/api/admin/apikeys?${params}`);
                    apiKeyList.value = data.content || [];
                    pagination.total = data.totalElements || 0;
                } catch (error) {
                    console.error('Failed to load API keys:', error);
                    apiKeyList.value = [];
                } finally {
                    loading.value = false;
                }
            };

            // 加载申请列表
            const loadApplications = async () => {
                applicationsLoading.value = true;
                try {
                    const params = new URLSearchParams({
                        page: applicationPagination.currentPage - 1,
                        size: applicationPagination.pageSize
                    });

                    const response = await apiRequest(`/api/admin/applications?${params}`);
                    // 后端返回格式：{ success: true, message: "查询成功", data: Page对象 }
                    if (response.success && response.data) {
                        applicationList.value = response.data.content || [];
                        applicationPagination.total = response.data.totalElements || 0;
                    } else {
                        applicationList.value = [];
                        applicationPagination.total = 0;
                    }
                } catch (error) {
                    console.error('Failed to load applications:', error);
                    applicationList.value = [];
                } finally {
                    applicationsLoading.value = false;
                }
            };

            // 刷新数据
            const refreshData = async () => {
                if (activeMenu.value === 'apikeys') {
                    await Promise.all([loadStats(), loadApiKeys()]);
                } else if (activeMenu.value === 'applications') {
                    await Promise.all([loadApplicationStats(), loadApplications()]);
                } else if (activeMenu.value === 'statistics') {
                    await loadStatisticsData();
                } else if (activeMenu.value === 'logs') {
                    await loadSystemLogsData();
                }
                ElMessage.success('数据刷新成功');
            };

            // 搜索API Keys
            const searchApiKeys = () => {
                pagination.currentPage = 1;
                loadApiKeys();
            };

            // 重置搜索
            const resetSearch = () => {
                searchForm.keyword = '';
                searchForm.status = '';
                pagination.currentPage = 1;
                loadApiKeys();
            };

            // 分页处理
            const handleSizeChange = (size) => {
                pagination.pageSize = size;
                pagination.currentPage = 1;
                loadApiKeys();
            };

            const handleCurrentChange = (page) => {
                pagination.currentPage = page;
                loadApiKeys();
            };

            // 申请分页处理
            const handleApplicationSizeChange = (size) => {
                applicationPagination.pageSize = size;
                applicationPagination.currentPage = 1;
                loadApplications();
            };

            const handleApplicationCurrentChange = (page) => {
                applicationPagination.currentPage = page;
                loadApplications();
            };

            // 获取状态类型
            const getStatusType = (status) => {
                const statusMap = {
                    'active': 'success',
                    'inactive': 'danger',
                    'disabled': 'danger',
                    'expired': 'warning',
                    'enabled': 'success',
                    'ACTIVE': 'success',
                    'INACTIVE': 'danger',
                    'DISABLED': 'danger',
                    'EXPIRED': 'warning',
                    'ENABLED': 'success'
                };
                return statusMap[status] || 'info';
            };

            // 获取状态文本
            const getStatusText = (status) => {
                const statusMap = {
                    'active': '启用',
                    'inactive': '禁用',
                    'disabled': '禁用',
                    'expired': '过期',
                    'enabled': '启用',
                    'ACTIVE': '启用',
                    'INACTIVE': '禁用',
                    'DISABLED': '禁用',
                    'EXPIRED': '过期',
                    'ENABLED': '启用'
                };
                return statusMap[status] || status;
            };

            // 获取申请状态类型
            const getApplicationStatusType = (status) => {
                const statusMap = {
                    'PENDING': 'warning',
                    'APPROVED': 'success',
                    'REJECTED': 'danger'
                };
                return statusMap[status] || 'info';
            };

            // 获取申请状态文本
            const getApplicationStatusText = (status) => {
                const statusMap = {
                    'PENDING': '待审核',
                    'APPROVED': '已通过',
                    'REJECTED': '已拒绝'
                };
                return statusMap[status] || status;
            };

            // 获取权限列表
            const getPermissions = (permissions) => {
                if (!permissions) return [];
                return permissions.split(',').filter(p => p.trim());
            };

            // 格式化日期
            const formatDate = (dateStr) => {
                if (!dateStr) return '-';
                return new Date(dateStr).toLocaleString('zh-CN');
            };

            // 检查是否过期
            const isExpired = (expiresAt) => {
                if (!expiresAt) return false;
                return new Date(expiresAt) < new Date();
            };

            // 复制到剪贴板
            const copyToClipboard = async (text) => {
                try {
                    await navigator.clipboard.writeText(text);
                    ElMessage.success('已复制到剪贴板');
                } catch (error) {
                    ElMessage.error('复制失败');
                }
            };

            // 显示总体统计
            const showOverallStats = () => {
                dialogs.overallStats = true;
                nextTick(() => {
                    initOverallStatsChart();
                });
            };

            // 显示系统日志
            const showSystemLogs = async () => {
                dialogs.systemLogs = true;
                logsLoading.value = true;
                try {
                    const data = await apiRequest('/api/access-logs?page=0&size=100');
                    systemLogs.value = data.content || [];
                } catch (error) {
                    console.error('Failed to load system logs:', error);
                } finally {
                    logsLoading.value = false;
                }
            };

            // 显示API Key统计
            const showApiKeyStats = (apiKey) => {
                currentApiKey.value = apiKey;
                dialogs.apiKeyStats = true;
                nextTick(() => {
                    initApiKeyStatsChart(apiKey.id);
                });
            };

            // 显示API Key日志
            const showApiKeyLogs = async (apiKey) => {
                currentApiKey.value = apiKey;
                dialogs.apiKeyLogs = true;
                logsLoading.value = true;
                try {
                    const data = await apiRequest(`/api/access-logs/by-apikey/${apiKey.id}?page=0&size=100`);
                    apiKeyLogs.value = data.content || [];
                } catch (error) {
                    console.error('Failed to load API key logs:', error);
                } finally {
                    logsLoading.value = false;
                }
            };

            // 查看申请详情
            const viewApplicationDetail = (application) => {
                currentApplication.value = application;
                dialogs.applicationDetail = true;
            };

            // 通过申请
            const approveApplication = async (application) => {
                try {
                    await apiRequest(`/api/admin/applications/${application.id}/approve`, {
                        method: 'POST',
                        body: JSON.stringify({
                            reviewer: 'admin',
                            remark: '申请通过'
                        })
                    });
                    ElMessage.success('申请已通过');
                    dialogs.applicationDetail = false;
                    await loadApplications();
                    await loadApplicationStats();
                } catch (error) {
                    console.error('Failed to approve application:', error);
                }
            };

            // 拒绝申请
            const rejectApplication = async (application) => {
                try {
                    const {value: comment} = await ElMessageBox.prompt('请输入拒绝理由', '拒绝申请', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPlaceholder: '请输入拒绝理由'
                    });

                    await apiRequest(`/api/admin/applications/${application.id}/reject`, {
                        method: 'POST',
                        body: JSON.stringify({
                            reviewer: 'admin',
                            remark: comment || '申请被拒绝'
                        })
                    });
                    ElMessage.success('申请已拒绝');
                    dialogs.applicationDetail = false;
                    await loadApplications();
                    await loadApplicationStats();
                } catch (error) {
                    if (error !== 'cancel') {
                        console.error('Failed to reject application:', error);
                    }
                }
            };

            // 显示创建对话框
            const showCreateDialog = () => {
                isEditing.value = false;
                resetApiKeyForm();
                dialogs.createEdit = true;
            };

            // 编辑API Key
            const editApiKey = (apiKey) => {
                isEditing.value = true;
                currentApiKey.value = apiKey;
                Object.assign(apiKeyForm, {
                    name: apiKey.name,
                    description: apiKey.description || '',
                    permissions: getPermissions(apiKey.permissions),
                    expiresAt: apiKey.expiresAt
                });
                dialogs.createEdit = true;
            };

            // 重置表单
            const resetApiKeyForm = () => {
                Object.assign(apiKeyForm, {
                    name: '',
                    description: '',
                    permissions: [],
                    expiresAt: ''
                });
            };

            // 提交表单
            const submitApiKeyForm = async () => {
                submitting.value = true;
                try {
                    // 表单验证
                    if (!apiKeyForm.name || apiKeyForm.name.trim() === '') {
                        ElMessage.error('请输入API Key名称');
                        return;
                    }
                    
                    if (!apiKeyForm.permissions || apiKeyForm.permissions.length === 0) {
                        ElMessage.error('请选择至少一个权限');
                        return;
                    }

                    const formData = {
                        name: apiKeyForm.name.trim(),
                        description: apiKeyForm.description || '',
                        permissions: Array.isArray(apiKeyForm.permissions) ? apiKeyForm.permissions.join(',') : apiKeyForm.permissions,
                        expiresAt: apiKeyForm.expiresAt || null,
                        operatorId: 'admin'
                    };

                    console.log('Submitting form data:', formData);

                    if (isEditing.value) {
                        await apiRequest(`/api/admin/apikeys/${currentApiKey.value.id}`, {
                            method: 'PUT',
                            body: JSON.stringify(formData)
                        });
                        ElMessage.success('API Key更新成功');
                    } else {
                        await apiRequest('/api/admin/apikeys', {
                            method: 'POST',
                            body: JSON.stringify(formData)
                        });
                        ElMessage.success('API Key创建成功');
                    }

                    dialogs.createEdit = false;
                    await refreshData();
                } catch (error) {
                    console.error('Failed to submit form:', error);
                    ElMessage.error('提交失败: ' + (error.message || '未知错误'));
                } finally {
                    submitting.value = false;
                }
            };

            // 切换API Key状态
            const toggleApiKeyStatus = async (apiKey) => {
                try {
                    await apiRequest(`/api/admin/apikeys/${apiKey.id}/toggle`, {
                        method: 'PUT',
                        body: JSON.stringify({operatorId: 'admin'})
                    });
                    ElMessage.success('状态切换成功');
                    await loadApiKeys();
                } catch (error) {
                    console.error('Failed to toggle status:', error);
                }
            };

            // 删除API Key
            const deleteApiKey = async (apiKey) => {
                try {
                    await ElMessageBox.confirm(
                        `确定要删除API Key "${apiKey.name}" 吗？`,
                        '确认删除',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    );

                    await apiRequest(`/api/admin/apikeys/${apiKey.id}`, {
                        method: 'DELETE',
                        body: JSON.stringify({operatorId: 'admin'})
                    });

                    ElMessage.success('删除成功');
                    await refreshData();
                } catch (error) {
                    if (error !== 'cancel') {
                        console.error('Failed to delete API key:', error);
                    }
                }
            };

            // 关闭弹窗
            const handleClose = (done) => {
                if (done) done();
            };

            // 初始化总体统计图表
            const initOverallStatsChart = () => {
                const chartDom = document.getElementById('overallStatsChart');
                if (!chartDom) return;

                chartDom.style.width = '100%';
                chartDom.style.height = '400px';

                const myChart = echarts.init(chartDom);

                const option = {
                    title: {
                        text: 'API Key统计概览',
                        left: 'center',
                        textStyle: {
                            fontSize: 16,
                            fontWeight: 'bold'
                        }
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        top: 'middle',
                        textStyle: {
                            fontSize: 12
                        }
                    },
                    series: [
                        {
                            name: 'API Key状态',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            center: ['60%', '50%'],
                            avoidLabelOverlap: false,
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '18',
                                    fontWeight: 'bold'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: [
                                {value: stats.activeKeys, name: '活跃', itemStyle: {color: '#67C23A'}},
                                {value: stats.expiredKeys, name: '过期', itemStyle: {color: '#E6A23C'}},
                                {
                                    value: stats.totalKeys - stats.activeKeys - stats.expiredKeys,
                                    name: '禁用',
                                    itemStyle: {color: '#F56C6C'}
                                }
                            ]
                        }
                    ]
                };

                myChart.setOption(option);

                window.addEventListener('resize', () => {
                    myChart.resize();
                });

                setTimeout(() => {
                    myChart.resize();
                }, 100);
            };

            // 初始化API Key统计图表
            const initApiKeyStatsChart = async (apiKeyId) => {
                const chartDom = document.getElementById('apiKeyStatsChart');
                if (!chartDom) return;

                chartDom.style.width = '100%';
                chartDom.style.height = '400px';

                const myChart = echarts.init(chartDom);

                try {
                    const data = await apiRequest(`/api/admin/apikeys/${apiKeyId}/stats`);

                    const option = {
                        title: {
                            text: 'API Key使用统计',
                            left: 'center',
                            textStyle: {
                                fontSize: 16,
                                fontWeight: 'bold'
                            }
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'cross'
                            }
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: data.dates || [],
                            axisLabel: {
                                rotate: 45
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '请求次数'
                        },
                        series: [
                            {
                                name: '请求次数',
                                type: 'line',
                                data: data.requests || [],
                                smooth: true,
                                itemStyle: {
                                    color: '#409EFF'
                                },
                                areaStyle: {
                                    color: {
                                        type: 'linear',
                                        x: 0,
                                        y: 0,
                                        x2: 0,
                                        y2: 1,
                                        colorStops: [{
                                            offset: 0, color: 'rgba(64, 158, 255, 0.3)'
                                        }, {
                                            offset: 1, color: 'rgba(64, 158, 255, 0.1)'
                                        }]
                                    }
                                }
                            }
                        ]
                    };

                    myChart.setOption(option);

                    window.addEventListener('resize', () => {
                        myChart.resize();
                    });

                    setTimeout(() => {
                        myChart.resize();
                    }, 100);

                } catch (error) {
                    console.error('Failed to load API key stats:', error);
                    ElMessage.error('加载统计数据失败');
                }
            };

            // 组件挂载时加载数据
            onMounted(() => {
                // 检查URL hash，如果是#applications则切换到申请审核页面
                const hash = window.location.hash;
                if (hash === '#applications') {
                    setActiveMenu('applications');
                } else {
                    setActiveMenu('apikeys');
                }
            });

            // 加载统计数据
            const loadStatisticsData = async () => {
                loading.value = true;
                try {
                    const params = new URLSearchParams();
                    if (statisticsFilter.dateRange && statisticsFilter.dateRange.length === 2) {
                        params.append('startDate', statisticsFilter.dateRange[0]);
                        params.append('endDate', statisticsFilter.dateRange[1]);
                    }
                    if (statisticsFilter.apiKeyId) {
                        params.append('apiKeyId', statisticsFilter.apiKeyId);
                    }

                    const data = await apiRequest(`/api/admin/statistics?${params}`);
                    Object.assign(stats, data);
                    
                    // 初始化统计图表
                    nextTick(() => {
                        initStatisticsChart(data);
                    });
                } catch (error) {
                    console.error('Failed to load statistics:', error);
                } finally {
                    loading.value = false;
                }
            };

            // 加载系统日志数据
            const loadSystemLogsData = async () => {
                logsLoading.value = true;
                try {
                    const params = new URLSearchParams({
                        page: logsPagination.currentPage - 1,
                        size: logsPagination.pageSize
                    });

                    if (logsFilter.dateRange && logsFilter.dateRange.length === 2) {
                        params.append('startTime', logsFilter.dateRange[0] + 'T00:00:00');
                        params.append('endTime', logsFilter.dateRange[1] + 'T23:59:59');
                    }
                    if (logsFilter.apiKeyId) {
                        params.append('apiKeyValue', logsFilter.apiKeyId);
                    }
                    if (logsFilter.statusCode) {
                        params.append('responseStatus', logsFilter.statusCode);
                    }

                    const data = await apiRequest(`/api/access-logs?${params}`);
                    systemLogsList.value = data.content || [];
                    logsPagination.total = data.totalElements || 0;
                } catch (error) {
                    console.error('Failed to load system logs:', error);
                    systemLogsList.value = [];
                } finally {
                    logsLoading.value = false;
                }
            };

            // 重置统计筛选条件
            const resetStatisticsFilter = () => {
                statisticsFilter.dateRange = [];
                statisticsFilter.apiKeyId = '';
                loadStatisticsData();
            };

            // 重置日志筛选条件
            const resetLogsFilter = () => {
                logsFilter.dateRange = [];
                logsFilter.apiKeyId = '';
                logsFilter.statusCode = '';
                logsPagination.currentPage = 1;
                loadSystemLogsData();
            };

            // 日志分页处理
            const handleLogsSizeChange = (size) => {
                logsPagination.pageSize = size;
                logsPagination.currentPage = 1;
                loadSystemLogsData();
            };

            const handleLogsCurrentChange = (page) => {
                logsPagination.currentPage = page;
                loadSystemLogsData();
            };

            // 初始化统计图表
            const initStatisticsChart = (data) => {
                const chartDom = document.getElementById('statisticsChart');
                if (!chartDom) return;

                chartDom.style.width = '100%';
                chartDom.style.height = '400px';

                const myChart = echarts.init(chartDom);

                const option = {
                    title: {
                        text: 'API使用统计',
                        left: 'center',
                        textStyle: {
                            fontSize: 16,
                            fontWeight: 'bold'
                        }
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross'
                        }
                    },
                    legend: {
                        data: ['请求次数', '错误次数'],
                        top: 30
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        top: '15%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: data.dates || [],
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '次数'
                    },
                    series: [
                        {
                            name: '请求次数',
                            type: 'line',
                            data: data.requests || [],
                            smooth: true,
                            itemStyle: {
                                color: '#409EFF'
                            },
                            areaStyle: {
                                color: {
                                    type: 'linear',
                                    x: 0,
                                    y: 0,
                                    x2: 0,
                                    y2: 1,
                                    colorStops: [{
                                        offset: 0, color: 'rgba(64, 158, 255, 0.3)'
                                    }, {
                                        offset: 1, color: 'rgba(64, 158, 255, 0.1)'
                                    }]
                                }
                            }
                        },
                        {
                            name: '错误次数',
                            type: 'line',
                            data: data.errors || [],
                            smooth: true,
                            itemStyle: {
                                color: '#F56C6C'
                            }
                        }
                    ]
                };

                myChart.setOption(option);

                window.addEventListener('resize', () => {
                    myChart.resize();
                });

                setTimeout(() => {
                    myChart.resize();
                }, 100);
            };

            return {
                // 响应式数据
                loading,
                applicationsLoading,
                logsLoading,
                submitting,
                isEditing,
                activeMenu,
                stats,
                applicationStats,
                apiKeyList,
                applicationList,
                systemLogsList,
                searchForm,
                pagination,
                applicationPagination,
                logsPagination,
                statisticsFilter,
                logsFilter,
                dialogs,
                currentApiKey,
                currentApplication,
                systemLogs,
                apiKeyLogs,
                apiKeyForm,
                formRules,

                // 方法
                getPageTitle,
                setActiveMenu,
                logout,
                refreshData,
                searchApiKeys,
                resetSearch,
                handleSizeChange,
                handleCurrentChange,
                handleApplicationSizeChange,
                handleApplicationCurrentChange,
                handleLogsSizeChange,
                handleLogsCurrentChange,
                loadStatisticsData,
                loadSystemLogsData,
                resetStatisticsFilter,
                resetLogsFilter,
                getStatusType,
                getStatusText,
                getApplicationStatusType,
                getApplicationStatusText,
                getPermissions,
                formatDate,
                isExpired,
                copyToClipboard,
                showOverallStats,
                showSystemLogs,
                showApiKeyStats,
                showApiKeyLogs,
                viewApplicationDetail,
                approveApplication,
                rejectApplication,
                showCreateDialog,
                editApiKey,
                submitApiKeyForm,
                toggleApiKeyStatus,
                deleteApiKey,
                handleClose,

                // 图标
                Key: ElementPlusIconsVue.Key,
                TrendCharts: ElementPlusIconsVue.TrendCharts,
                Document: ElementPlusIconsVue.Document,
                Plus: ElementPlusIconsVue.Plus,
                Refresh: ElementPlusIconsVue.Refresh,
                Search: ElementPlusIconsVue.Search,
                RefreshLeft: ElementPlusIconsVue.RefreshLeft,
                CopyDocument: ElementPlusIconsVue.CopyDocument,
                Edit: ElementPlusIconsVue.Edit,
                Delete: ElementPlusIconsVue.Delete,
                Timer: ElementPlusIconsVue.Timer,
                Warning: ElementPlusIconsVue.Warning
            };
        }
    });

    // 注册所有图标
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }

    app.use(ElementPlus);
    app.mount('#app');
</script>
</body>
</html>